import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import router from './index'
import Store from '@/store'
import Msg from '@/utils/msg'
import Auth from '@/auth'

NProgress.configure({showSpinner: false})// NProgress Configuration

// permissiom judge function
function hasPermission(modules, permissionRoles) {
  // if (modules.indexOf('super') >= 0) return true // admin permission passed directly
  if (!permissionRoles) return true
  return modules.some(role => permissionRoles.indexOf(role) >= 0)
}

const whiteList = ['/login']// no redirect whitelist

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (Store.getters.token) { // determine if there has token
    if (to.path === '/login') {
      next({path: '/'})
      NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
    } else {
      if (!Store.getters.user) { // 表示当前用户还没有拉取到用户信息，先去拉取
        Auth.getUserByToken(Store.getters.token).then((res)=>{
          if(res.code==0){
            let user = res.data;
            Store.commit('SET_USER',user)
            let modules = user.company.modules // note: modules must be a array! such as: ['editor','develop']
            Store.dispatch('GenerateRoutes', {modules}).then(() => { // 根据roles权限生成可访问的路由表
              router.addRoutes(Store.getters.addedRouters) // 动态添加可访问路由表  真正加到路由表中去
              next({...to, replace: true}) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
            })
          }else{
            Store.dispatch('logOut').then(() => {
              Msg.error('登录信息已过期，请重新登录！')
              next({path: '/login'})
            })
          }
        })
      } else {
        /* 判断有没有这个页面的权限*/
        console.log("to_page:",to)
        if (hasPermission(Store.getters.user.modules, to.meta.modules)) {
          next()
        } else {
          next({path: '/401', replace: true, query: {noGoBack: true}})
        }
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) { // 在免登录白名单，直接进入
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }

})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
